// pages/record/meal.js
const { post, upload } = require('../../utils/request');

Page({

    /**
     * 页面的初始数据
     */
    data: {
        mealType: '早餐',
        foods: [],
        totalCalories: 0,
        totalProtein: 0,
        totalCarbs: 0,
        totalFat: 0,
        notes: '',
        images: []
    },

    /**
     * 生命周期函数--监听页面加载
     */
    onLoad(options) {
        if (options.type) {
            this.setData({
                mealType: options.type
            });
        }
    },

    /**
     * 生命周期函数--监听页面初次渲染完成
     */
    onReady() {

    },

    /**
     * 生命周期函数--监听页面显示
     */
    onShow() {

    },

    /**
     * 生命周期函数--监听页面隐藏
     */
    onHide() {

    },

    /**
     * 生命周期函数--监听页面卸载
     */
    onUnload() {

    },

    /**
     * 页面相关事件处理函数--监听用户下拉动作
     */
    onPullDownRefresh() {

    },

    /**
     * 页面上拉触底事件的处理函数
     */
    onReachBottom() {

    },

    /**
     * 用户点击右上角分享
     */
    onShareAppMessage() {

    },

    // 选择餐点类型
    selectMealType(e) {
        const typeMap = {
            'breakfast': '早餐',
            'lunch': '午餐',
            'dinner': '晚餐',
            'snack': '加餐'
        };
        const type = e.currentTarget.dataset.type;
        this.setData({ mealType: typeMap[type] });
    },

    // 显示食物选择器
    showFoodSelector() {
        wx.navigateTo({
            url: '/pages/food/selector'
        });
    },

    // 删除食物
    deleteFood(e) {
        const index = e.currentTarget.dataset.index;
        const foods = this.data.foods;
        foods.splice(index, 1);
        this.setData({ foods });
        this.calculateNutrition();
    },

    // 计算营养摄入
    calculateNutrition() {
        const foods = this.data.foods;
        let totalCalories = 0;
        let totalProtein = 0;
        let totalCarbs = 0;
        let totalFat = 0;

        foods.forEach(food => {
            totalCalories += food.calories || 0;
            totalProtein += food.protein || 0;
            totalCarbs += food.carbs || 0;
            totalFat += food.fat || 0;
        });

        this.setData({
            totalCalories: totalCalories.toFixed(1),
            totalProtein: totalProtein.toFixed(1),
            totalCarbs: totalCarbs.toFixed(1),
            totalFat: totalFat.toFixed(1)
        });
    },

    // 处理备注输入
    onNotesChange(e) {
        this.setData({
            notes: e.detail.value
        });
    },

    // 选择图片
    async chooseImage() {
        try {
            const res = await wx.chooseImage({
                count: 9 - this.data.images.length,
                sizeType: ['compressed'],
                sourceType: ['album', 'camera']
            });

            wx.showLoading({
                title: '上传中...'
            });

            const uploadTasks = res.tempFilePaths.map(path => {
                return upload('/upload/image', path, 'image');
            });

            const uploadResults = await Promise.all(uploadTasks);
            const newImages = uploadResults.map(result => result.url);

            this.setData({
                images: [...this.data.images, ...newImages]
            });

            wx.hideLoading();
            
            wx.showToast({
                title: '上传成功',
                icon: 'success'
            });
        } catch (error) {
            console.error('上传图片失败:', error);
            wx.hideLoading();
            wx.showToast({
                title: '上传失败',
                icon: 'none'
            });
        }
    },

    // 删除图片
    deleteImage(e) {
        const index = e.currentTarget.dataset.index;
        const images = this.data.images;
        images.splice(index, 1);
        this.setData({ images });
    },

    // 表单提交
    async handleSubmit() {
        const { mealType, foods, totalCalories, totalProtein, totalCarbs, totalFat, notes, images } = this.data;

        if (!mealType) {
            wx.showToast({
                title: '请选择餐点类型',
                icon: 'none'
            });
            return;
        }

        if (foods.length === 0) {
            wx.showToast({
                title: '请添加食物',
                icon: 'none'
            });
            return;
        }

        try {
            const data = {
                mealType,
                foods,
                totalCalories: parseFloat(totalCalories),
                totalProtein: parseFloat(totalProtein),
                totalCarbs: parseFloat(totalCarbs),
                totalFat: parseFloat(totalFat),
                notes,
                images,
                date: new Date().toISOString().split('T')[0]
            };

            await post('/records/diet', data);
            
            wx.showToast({
                title: '记录成功',
                icon: 'success'
            });

            setTimeout(() => {
                wx.navigateBack();
            }, 1500);
        } catch (error) {
            wx.showToast({
                title: '记录失败',
                icon: 'none'
            });
        }
    }
})